package com.daka;

import java.io.IOException;
import java.security.MessageDigest;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;

import com.alibaba.fastjson.JSON;
import com.daka.comm.PostData;
import com.daka.daka.req.DakaReq;
import com.daka.login.req.UserLogin;
import com.daka.login.res.LoginRespon;

public class DakaClient {
	
	private static String loginUrl = "http://222.85.157.65:28001/PersonManageSystem/web.do";
	
	String username = "1122";
	//String username = "sunchaohong";
	String password = "123456";
	
	public static void main(String[] args) {
		DakaClient demo = new DakaClient();
		String loginRes = demo.login();
		System.out.println("登陆返回："+loginRes);
		LoginRespon parseObject = JSON.parseObject(loginRes, LoginRespon.class);
		String daka = demo.daka(parseObject);
		System.out.println("打卡返回："+daka);
	}
	
	private String daka(LoginRespon logginres) {
		PostData data = new PostData();
		data.setMethod("personClockIn");
		DakaReq daka = new DakaReq();
		// 查询设备列表可带 未做
		daka.setIbeaconId("2c907d536b870bc5016b8720393300c6--");
		
		// 从登陆出可以获得
		//daka.setPersonId("2c907d5369fd292a016a0b16ad03021c");
		daka.setPersonId(logginres.getData().getUser().getPersonId());
		//daka.setPhoneCode("6569b413f6db3e2b");
		daka.setPhoneCode(logginres.getData().getPersonPhone().getPhoneCode());
		data.setParam(getParamData(JSON.toJSONString(daka)));
		String jsonToEncode = jsonToEncode(JSON.toJSONString(data));
		String resData = doPost(jsonToEncode, loginUrl);
		return resData;
	}
	
	private String login() {
		PostData data = new PostData();
		data.setMethod("getPersonLogin");
		UserLogin user = new UserLogin();
		user.setLogin(username); // username
		user.setPassword(password);
		data.setParam(getParamData(JSON.toJSONString(user)));
		String jsonToEncode = jsonToEncode(JSON.toJSONString(data));
		String resData = doPost(jsonToEncode, loginUrl);
		return resData;
	}
 
	private String getParamData(String json) {
		@SuppressWarnings("unchecked")
		Map<String, String> map = (Map<String, String>) JSON.parse(json);
		map.put("md5", getMd5Str(json));
		String jsonString = JSON.toJSONString(map);
		return jsonString;
	}
	
	private String getMd5Str(String json) {
		String result = jsonToEncode(json);
		result+="&uuid=CD42B6FC-A721-4FD2-9F26-A7CFC83BE21F";
		String md5 = MD5(result);
		return md5;
	}
	
	private String jsonToEncode(String str) {
		@SuppressWarnings("unchecked")
		Map<String, String> map = (Map<String, String>) JSON.parse(str);
		Set<String> keySet = map.keySet();
		List<String> sortList = new ArrayList<String>();
		for (String key : keySet) {
			sortList.add(key);
		}
		sortList.sort(new Comparator<String>() {
			@Override
			public int compare(String arg1, String arg2) {
				return arg1.compareTo(arg2);
			}
		});
		String result = "";
		for (String key : sortList) {
			result+= "&"+key+"="+map.get(key);
		}
		return result.substring(1);
	}
	
	private String  MD5(String data){
		StringBuffer sb = new StringBuffer(32);
		MessageDigest md;
		try {
			md = MessageDigest.getInstance("MD5");
			byte[] array = md.digest(data.getBytes("utf-8"));
			for (int i = 0; i < array.length; i++) {
				sb.append(Integer.toHexString((array[i] & 0xFF) | 0x100).substring(1, 3));
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return sb.toString();
	}
	
	
	private String doPost(String json,String url) {
		// 获得Http客户端(可以理解为:你得先有一个浏览器;注意:实际上HttpClient与浏览器是不一样的)
		CloseableHttpClient httpClient = HttpClientBuilder.create().build();
 
		// 创建Post请求
		HttpPost httpPost = new HttpPost(url);
		StringEntity entity = new StringEntity(json, "UTF-8");
		// post请求是将参数放在请求体里面传过去的;这里将entity放入post请求体中
		httpPost.setEntity(entity);
 
		httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded; charset=utf-8");
		httpPost.setHeader("accept", "application/json;charset=utf8");
		httpPost.setHeader("User-Agent", " okhttp/3.6.0");
		httpPost.setHeader("Accept-Encoding", "gzip");
		
		String resData = null;
		// 响应模型
		CloseableHttpResponse response = null;
		try {
			// 由客户端执行(发送)Post请求
			response = httpClient.execute(httpPost);
			// 从响应模型中获取响应实体
			HttpEntity responseEntity = response.getEntity();
 
			System.out.println("响应状态为:" + response.getStatusLine());
			if (responseEntity != null) {
				System.out.println("响应内容长度为:" + responseEntity.getContentLength());
				resData = EntityUtils.toString(responseEntity);
				System.out.println("响应内容为:" + resData);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				// 释放资源
				if (httpClient != null) {
					httpClient.close();
				}
				if (response != null) {
					response.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return resData;
	}
}
